#!/usr/bin/env python3
"""
测试Ford API响应数据结构
帮助优化Key Features和价格的提取路径
"""

import requests
import json

def test_api_response():
    """测试API响应数据结构"""
    
    # API配置
    api_url = "https://www.servicescache.ford.com/api/vehicle-model/v1/load"
    params = {
        'locale': 'en_GB',
        'retrieve': 'images,specs,featuresMkt,selectedMkt,featureImages,featureSpecs,keyFeatures,keyFeaturesModel,keyFeaturesWalkup,uscCodes,prices,featurePrices,content,packages',
        'config': 'WAEGB-CGE-2022-FocusMCAGBR202450~ACMAA_VS-DH',  # Titanium
        'displayContext': 'VISTA',
        'suppressDisplayContext': 'true',
        'namedConfig': 'default'
    }
    
    try:
        print("🔍 测试Ford API响应数据结构...")
        response = requests.get(api_url, params=params, timeout=30)
        
        if response.status_code == 200:
            data = response.json()
            
            print("✅ API调用成功")
            print(f"响应数据大小: {len(json.dumps(data))} 字符")
            
            # 分析数据结构
            print("\n📊 数据结构分析:")
            analyze_data_structure(data, max_depth=3)
            
            # 寻找Key Features
            print("\n🔑 寻找Key Features...")
            find_key_features(data)
            
            # 寻找价格信息
            print("\n💰 寻找价格信息...")
            find_price_info(data)
            
            # 保存完整响应用于调试
            with open('./release/api_response_debug.json', 'w', encoding='utf-8') as f:
                json.dump(data, f, indent=2, ensure_ascii=False)
            print(f"\n💾 完整API响应已保存到: ./release/api_response_debug.json")
            
        else:
            print(f"❌ API调用失败: {response.status_code}")
            print(f"响应内容: {response.text}")
            
    except Exception as e:
        print(f"❌ 测试失败: {e}")

def analyze_data_structure(data, prefix="", max_depth=3, current_depth=0):
    """分析数据结构"""
    if current_depth >= max_depth:
        return
    
    if isinstance(data, dict):
        for key, value in data.items():
            if isinstance(value, dict):
                print(f"{prefix}{key}/ (字典, {len(value)} 个键)")
                if current_depth < max_depth - 1:
                    analyze_data_structure(value, f"{prefix}  ", max_depth, current_depth + 1)
            elif isinstance(value, list):
                print(f"{prefix}{key}[] (列表, {len(value)} 个元素)")
                if value and current_depth < max_depth - 1:
                    print(f"{prefix}  示例元素类型: {type(value[0])}")
                    if isinstance(value[0], dict):
                        analyze_data_structure(value[0], f"{prefix}    ", max_depth, current_depth + 1)
            else:
                print(f"{prefix}{key}: {type(value).__name__}")
    elif isinstance(data, list):
        print(f"{prefix}列表 ({len(data)} 个元素)")
        if data:
            print(f"{prefix}  元素类型: {type(data[0])}")

def find_key_features(data, path=""):
    """递归查找Key Features相关的数据"""
    if isinstance(data, dict):
        for key, value in data.items():
            current_path = f"{path}.{key}" if path else key
            
            # 检查是否是Key Features相关的字段
            if any(keyword in key.lower() for keyword in ['feature', 'walkup', 'combined']):
                print(f"  🎯 发现特性相关字段: {current_path}")
                if isinstance(value, list):
                    print(f"    列表长度: {len(value)}")
                    if value:
                        print(f"    第一个元素: {value[0]}")
                        if len(value) > 1:
                            print(f"    第二个元素: {value[1]}")
                elif isinstance(value, dict):
                    print(f"    字典键: {list(value.keys())}")
                else:
                    print(f"    值: {value}")
            
            # 递归搜索
            if isinstance(value, (dict, list)) and len(str(value)) < 10000:  # 避免过大的数据
                find_key_features(value, current_path)
    
    elif isinstance(data, list):
        for i, item in enumerate(data[:3]):  # 只检查前3个元素
            find_key_features(item, f"{path}[{i}]")

def find_price_info(data, path=""):
    """递归查找价格相关的数据"""
    if isinstance(data, dict):
        for key, value in data.items():
            current_path = f"{path}.{key}" if path else key
            
            # 检查是否是价格相关的字段
            if any(keyword in key.lower() for keyword in ['price', 'cost', 'amount', 'total']):
                print(f"  💰 发现价格相关字段: {current_path}")
                if isinstance(value, list):
                    print(f"    列表长度: {len(value)}")
                    if value:
                        print(f"    第一个元素: {value[0]}")
                elif isinstance(value, dict):
                    print(f"    字典键: {list(value.keys())}")
                else:
                    print(f"    值: {value}")
            
            # 递归搜索（限制深度）
            if isinstance(value, (dict, list)) and len(str(value)) < 5000:
                find_price_info(value, current_path)
    
    elif isinstance(data, list):
        for i, item in enumerate(data[:2]):  # 只检查前2个元素
            find_price_info(item, f"{path}[{i}]")

if __name__ == "__main__":
    test_api_response()
